package com.jcl.recruit.wechat.logic;

import com.jcl.core.common.page.PageResult;
import com.jcl.core.constants.ChannelSourceConstant;
import com.jcl.core.utils.StringUtils;
import com.jcl.core.web.model.UserToken;
import com.jcl.core.web.utils.SecurityUtils;
import com.jcl.recruit.console.logic.ConsoleUserAccessLogic;
import com.jcl.recruit.console.model.ConsoleUserAccess;
import com.jcl.recruit.core.config.SystemConfig;
import com.jcl.recruit.core.constants.UserExternalLoginConstant;
import com.jcl.recruit.searchresume.logic.SearchResumeRecordLogic;
import com.jcl.recruit.searchresume.model.SearchResumeRecord;
import com.jcl.recruit.server.elastic.SearchResumeServer;
import com.jcl.recruit.server.elastic.vo.SearchParamEntity;
import com.jcl.recruit.server.elastic.vo.SearchResumeRecordVo;
import com.jcl.recruit.wechat.utils.WechatUtils;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class WechatPushLogic {

    @Autowired
    private ConsoleUserAccessLogic consoleUserAccessLogic;
    @Autowired
    private SearchResumeRecordLogic searchResumeRecordLogic;

    @Autowired
    private SearchResumeServer searchResumeServer;

    public int pushDownloadResumeMessage(String corpCode, String userId, String resumeId) {

        return 0;
    }

    /**
     * @param mapList
     * @param accessToken
     */
    public int pushRecommendMessage(List<Map<String, String>> mapList, String accessToken) {

        Map<String, String> tempCount = new HashMap<>();
        if (CollectionUtils.isNotEmpty(mapList)) {
            for (Map<String, String> map : mapList) {
                tempCount.put(map.get("来源"), String.valueOf(map.get("数量")));
            }
        }
        StringBuffer buffer = new StringBuffer();
        for (Map.Entry<String, String> entry : ChannelSourceConstant.sourceMap.entrySet()) {
            String number = tempCount.get(entry.getKey());
            buffer.append(entry.getValue())
                    .append(" : ")
                    .append(StringUtils.hasLength(number) ? number : 0)
                    .append("\n");
        }

        WechatUtils.TemplateScreenInfo screenInfo = new WechatUtils.TemplateScreenInfo();
        screenInfo.setCrawlingFirst(buffer.toString());
        screenInfo.setKeyword1("当天的简历数量，如上述");
        screenInfo.setKeyword2("李程");
        WechatUtils.TemplateInfo templateInfo = new WechatUtils.TemplateInfo<>();
        templateInfo.setUrl(null);
        templateInfo.setTemplate_id(SystemConfig.getWechatTemplateScreenId());
        templateInfo.setTouser("o-s3g0oIOuyy6AILxboClu8mYCgc");
        templateInfo.setData(screenInfo);

        Map<String, String> userMap = SystemConfig.getCrawlingPushUser();
        if (userMap.size() > 0) {
            for (Map.Entry<String, String> entry : userMap.entrySet()) {
                templateInfo.setTouser(entry.getKey());
                screenInfo.setKeyword2(entry.getValue());

                WechatUtils.sendTemplateMessage(accessToken, templateInfo);
            }
        } else {
            WechatUtils.sendTemplateMessage(accessToken, templateInfo);
        }
        return 1;
    }

    /**
     * @param userId
     * @param accessToken
     */
    public int pushRecommendMessage(Integer userId, String accessToken) {

        ConsoleUserAccess userAccess = consoleUserAccessLogic.findOneByUserId(userId,
                UserExternalLoginConstant.USER_ACCESS_CATEGORY_WECHAT);
        if (null != userAccess) {
            WechatUtils.TemplateInfo templateInfo = pushScreenMessage(userAccess, true);
            if (StringUtils.hasLength(templateInfo.getTouser())) {
                WechatUtils.sendTemplateMessage(accessToken, templateInfo);
                return 0;
            }
        }
        return 1;
    }

    /**
     * @param accessToken
     */
    public int pushRecommendMessage(String accessToken) {
        List<ConsoleUserAccess> userAccessList = consoleUserAccessLogic.findList(
                UserExternalLoginConstant.USER_ACCESS_CATEGORY_WECHAT,
                UserExternalLoginConstant.USER_ACCESS_STATUS_USED, UserExternalLoginConstant.USER_ACCESS_STATUS_UNUSED);
        if (CollectionUtils.isNotEmpty(userAccessList)) {
            for (ConsoleUserAccess userAccess : userAccessList) {
                if (null != userAccess.getUserId()) {
                    WechatUtils.TemplateInfo templateInfo = pushScreenMessage(userAccess, false);
                    if (StringUtils.hasLength(templateInfo.getTouser())) {
                        WechatUtils.sendTemplateMessage(accessToken, templateInfo);
                    }
                }
            }
            return userAccessList.size();
        }
        return 0;
    }

    public WechatUtils.TemplateInfo pushScreenMessage(ConsoleUserAccess userAccess, boolean isTest) {
        WechatUtils.TemplateInfo templateInfo = new WechatUtils.TemplateInfo<>();
        Integer number = 0;
        StringBuffer keyword1 = new StringBuffer();
        List<SearchResumeRecord> recordList = searchResumeRecordLogic.
                findListByWechat(userAccess.getCorpCode(), userAccess.getUserId());
        if (CollectionUtils.isNotEmpty(recordList)) {

            recordList = org.springframework.util.CollectionUtils.isEmpty(recordList) ? null : recordList;
            SearchParamEntity searchParamEntity = new SearchParamEntity();
            searchParamEntity.setCurPage(1);
            List<SearchResumeRecordVo> voList = new ArrayList<>();
            for (SearchResumeRecord record : recordList) {
                SearchResumeRecordVo vo = new SearchResumeRecordVo();
                BeanUtils.copyProperties(record, vo);
                voList.add(vo);
            }
            searchParamEntity.setResumeRecords(voList);

            PageResult result = searchResumeServer.resumePageList(searchParamEntity);

            number = Integer.parseInt(result.getTotal().toString());
            List<String> keywords = new ArrayList<>();
            List<String> educations = new ArrayList<>();
            List<String> cities = new ArrayList<>();
            List<Integer> workYears = new ArrayList<>();

            for (SearchResumeRecord record : recordList) {
                if (StringUtils.hasLength(record.getKeyword()) && !keywords.contains(record.getKeyword())) {
                    keywords.add(record.getKeyword());
                }
                if (StringUtils.hasLength(record.getEducation()) && !educations.contains(record.getEducation())) {
                    educations.add(record.getEducation());
                }
                if (StringUtils.hasLength(record.getCity()) && !cities.contains(record.getCity())) {
                    cities.add(record.getCity());
                }
                if (!workYears.contains(record.getWorkYear())) {
                    workYears.add(record.getWorkYear());
                }
            }
            if (keywords.isEmpty() && educations.isEmpty() && cities.isEmpty() && workYears.isEmpty()) {
            } else {
                if (!keywords.isEmpty()) {
                    String temp = keywords.toString();
                    keyword1.append(" ").append(temp.substring(1, temp.length() - 1)).append(" |");
                }
                if (!educations.isEmpty()) {
                    String temp = educations.toString();
                    keyword1.append(" ").append(temp.substring(1, temp.length() - 1)).append(" |");
                }
                if (!cities.isEmpty()) {
                    String temp = cities.toString();
                    keyword1.append(" ").append(temp.substring(1, temp.length() - 1)).append(" |");
                }
                if (!workYears.isEmpty()) {
                    String temp = workYears.toString();
                    keyword1.append(" ").append(temp.substring(1, temp.length())).append(" |");
                }
            }
        }
        if (number > 0) {
            WechatUtils.TemplateScreenInfo screenInfo = new WechatUtils.TemplateScreenInfo();
            if (keyword1.length() == 0) {
                screenInfo.setKeyword1("请设置推荐条件");
            } else {
                screenInfo.setKeyword1(keyword1.toString().substring(0, keyword1.length() - 1));
            }
            screenInfo.setFirst(number.toString());
            screenInfo.setKeyword2(userAccess.getNickname());
            templateInfo.setData(screenInfo);
            String state = WechatUtils.LOGIN_STATE + WechatUtils.LOGIN_STATE_SPLIT + userAccess.getCorpCode();
            String redirect_url = SystemConfig.getSystemWebUrl() + SystemConfig.getWechatLoginUrl();
            try {
                String redirect = URLEncoder.encode(redirect_url, "UTF-8");
                String url = WechatUtils.getWechatLoginUrl(redirect, state);
                templateInfo.setUrl(url);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            templateInfo.setTemplate_id(SystemConfig.getWechatTemplateScreenId());
            templateInfo.setTouser(userAccess.getExternalKey());
        }
        return templateInfo;
    }

    public UserToken createUserToken(ConsoleUserAccess userAccess) {
        UserToken userToken = new UserToken(userAccess.getCorpCode(),
                userAccess.getUserId().toString(), null, null, null,
                SecurityUtils.FROM_WECHAT_SCREEN);


        return userToken;
    }

    public static void main(String[] args) {
        WechatUtils.TemplateInfo templateInfo = new WechatUtils.TemplateInfo<>();
        WechatUtils.TemplateScreenInfo screenInfo = new WechatUtils.TemplateScreenInfo();
        String first = "";

        screenInfo.setFirst(first);
        screenInfo.setKeyword1("上海");
        screenInfo.setKeyword2("liuyy");
        templateInfo.setData(screenInfo);
        templateInfo.setUrl("http://www.baidu.com");
        templateInfo.setTemplate_id(SystemConfig.getWechatTemplateScreenId());
        templateInfo.setTouser("o-s3g0q_kl_vzdwCUICFCdk-h2NM");

        WechatUtils.sendTemplateMessage("13_iqsU-Yqlde_sMLCe0MPZU28-BFUSt3Kq01x9UUhJALdH01wxDQlTxUsaZ2aBwzK7OhCWVGJ2virsv4XWjInaZotjSymNl5AUbZrfQHkNzKZCKpEQSuaemwM0vwqJ5PrI7hE5-0s3IpOnw5SDCMWiAJALVF",
                templateInfo);
    }
}
